document.addEventListener('DOMContentLoaded', function() {
    // 元素引用
    const selectedCountEl = document.getElementById('selected-count');
    const comboCountEl = document.getElementById('combo-count');
    const totalBetsEl = document.getElementById('total-bets');
    const combinationsCountEl = document.getElementById('combinations-count');
    const combinationsListEl = document.getElementById('combinations-list');
    const prevPageBtn = document.getElementById('prev-page');
    const nextPageBtn = document.getElementById('next-page');
    const pageInfoEl = document.getElementById('page-info');
    const toastEl = document.getElementById('toast');
    const dataUrlInput = document.getElementById('data-url');
    const saveUrlBtn = document.getElementById('save-url-btn');

    // 当前页码
    let currentPage = 1;
    let totalPages = 0;

    // 显示提示消息
    function showToast(message, duration = 3000) {
        toastEl.textContent = message;
        toastEl.classList.add('show');

        setTimeout(() => {
            toastEl.classList.remove('show');
        }, duration);
    }

// 为结果选项绑定点击事件
    document.querySelectorAll('.col-result').forEach(el => {
        el.addEventListener('click', function() {
            const matchId = this.closest('.match-row').dataset.id;
            const result = this.dataset.result;
            // 发送请求到后端
            fetch('/toggle', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({match_id: matchId, result: result})
            }).then(res => res.json())
                .then(data => {
                    // 更新页面统计数据
                    document.getElementById('selected-count').textContent = data.selected_count;
                    document.getElementById('combo-count').textContent = data.combo_count;
                    document.getElementById('total-bets').textContent = data.total_bets;
                    // 切换选中样式
                    this.classList.toggle('selected');
                });
        });
    });

    // 保存数据链接
    saveUrlBtn.addEventListener('click', function() {
        const url = dataUrlInput.value.trim();

        if (!url) {
            showToast('请输入有效的数据链接');
            return;
        }

        fetch('/set-url', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ url: url })
        })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    showToast(data.message);
                    dataUrlInput.value = data.url;
                } else {
                    showToast(data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('保存链接失败，请重试');
            });
    });

    // 刷新数据按钮
    document.getElementById('refresh-btn').addEventListener('click', function() {
        showToast('正在刷新数据...');

        fetch('/refresh', {
            method: 'POST'
        })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    // 清空现有比赛列表
                    const matchesListEl = document.getElementById('matches-list');
                    matchesListEl.innerHTML = '';

                    // 添加新比赛数据
                    data.matches.forEach(match => {
                        const matchRow = document.createElement('div');
                        matchRow.className = 'match-row';
                        matchRow.dataset.id = match.id;

                        matchRow.innerHTML = `
                        <div class="match-col col-id">${match.id}</div>
                        <div class="match-col col-league">${match.league}</div>
                        <div class="match-col col-time">${match.time}</div>
                        <div class="match-col col-result result-3" data-result="3">
                            <div class="team">${match.home}</div>
                            <div class="odds">赔率: ${match.odds3}</div>
                        </div>
                        <div class="match-col col-result result-1" data-result="1">
                            <div class="team">平</div>
                            <div class="odds">赔率: ${match.odds1}</div>
                        </div>
                        <div class="match-col col-result result-0" data-result="0">
                            <div class="team">${match.away}</div>
                            <div class="odds">赔率: ${match.odds0}</div>
                        </div>
                    `;

                        matchesListEl.appendChild(matchRow);

                        // 为新添加的元素绑定点击事件
                        matchRow.querySelectorAll('.col-result').forEach(el => {
                            el.addEventListener('click', function() {
                                const mId = matchRow.dataset.id;
                                const res = this.dataset.result;

                                this.classList.toggle('selected');

                                fetch('/toggle', {
                                    method: 'POST',
                                    headers: {
                                        'Content-Type': 'application/json'
                                    },
                                    body: JSON.stringify({
                                        match_id: mId,
                                        result: res
                                    })
                                })
                                    .then(response => response.json())
                                    .then(data => {
                                        if (data.status === 'success') {
                                            selectedCountEl.textContent = data.selected_count;
                                            comboCountEl.textContent = data.combo_count;
                                            totalBetsEl.textContent = data.total_bets;
                                        }
                                    });
                            });
                        });
                    });

                    // 重置统计信息和组合列表
                    selectedCountEl.textContent = '0';
                    comboCountEl.textContent = '0';
                    totalBetsEl.textContent = '0';
                    combinationsListEl.innerHTML = '';
                    combinationsCountEl.textContent = '(0组)';

                    showToast('数据刷新成功');
                } else {
                    showToast('刷新失败');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('网络错误，请重试');
            });
    });

    // 生成组合按钮
    document.getElementById('generate-btn').addEventListener('click', function() {
        const selectedCount = parseInt(selectedCountEl.textContent);

        if (selectedCount < 9) {
            showToast(`请至少选择9场比赛，当前仅选择了${selectedCount}场`);
            return;
        }

        showToast('正在生成组合，请稍候...');

        fetch('/generate', {
            method: 'POST'
        })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    showToast(data.message);
                    combinationsCountEl.textContent = `(${data.count}组)`;
                    currentPage = 1;  // 重置到第一页
                    loadCombinations(currentPage);  // 加载第一页组合
                } else {
                    showToast(data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('生成失败，请重试');
            });
    });

    // 导出图片按钮
    document.getElementById('export-image-btn').addEventListener('click', function() {
        const comboCount = parseInt(combinationsCountEl.textContent.replace(/[^\d]/g, ''));

        if (comboCount === 0) {
            showToast('请先生成组合');
            return;
        }

        showToast('正在生成图片...');

        // 打开新窗口下载图片
        window.open('/export-image', '_blank');

        setTimeout(() => {
            showToast('图片生成成功，正在下载');
        }, 1000);
    });

    // 清空选择按钮
    document.getElementById('clear-btn').addEventListener('click', function() {
        // 清除所有选中状态
        document.querySelectorAll('.col-result.selected').forEach(el => {
            el.classList.remove('selected');
        });

        // 刷新数据以清除后端选择状态
        fetch('/refresh', {
            method: 'POST'
        })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    selectedCountEl.textContent = '0';
                    comboCountEl.textContent = '0';
                    totalBetsEl.textContent = '0';
                    combinationsListEl.innerHTML = '';
                    combinationsCountEl.textContent = '(0组)';
                    showToast('已清空所有选择');
                } else {
                    showToast('清空失败，请重试');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('网络错误，请重试');
            });
    });

    // 加载组合数据
    function loadCombinations(page) {
        fetch(`/load-combinations/${page}`)
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    // 清空现有组合列表
                    combinationsListEl.innerHTML = '';

                    // 添加新组合
                    data.combinations.forEach((combo, index) => {
                        const comboItem = document.createElement('div');
                        comboItem.className = 'combination-item';
                        comboItem.textContent = `组合 ${(page - 1) * 10 + index + 1}: ${combo}`;
                        combinationsListEl.appendChild(comboItem);
                    });

                    // 更新分页信息
                    currentPage = data.current_page;
                    totalPages = data.total_pages;
                    pageInfoEl.textContent = `第 ${currentPage} 页 / 共 ${totalPages} 页`;

                    // 更新分页按钮状态
                    prevPageBtn.disabled = currentPage <= 1;
                    nextPageBtn.disabled = currentPage >= totalPages;
                } else {
                    showToast('加载组合失败');
                }
            })
            .catch(error => {
                console.error('Error loading combinations:', error);
                showToast('加载组合失败，请重试');
            });
    }

    // 上一页按钮
    prevPageBtn.addEventListener('click', function() {
        if (currentPage > 1) {
            loadCombinations(currentPage - 1);
        }
    });

    // 下一页按钮
    nextPageBtn.addEventListener('click', function() {
        if (currentPage < totalPages) {
            loadCombinations(currentPage + 1);
        }
    });
});